package com.midian.action.mc.permission;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.midian.action.mc.common.AjaxAction;
import com.midian.common.annotation.FunctionAnnotationOverride;
import com.midian.common.exception.BizException;
import com.midian.common.system.SysStatic;
import com.midian.model.permission.Role;
import com.midian.service.permission.IRoleService;

/**
 * 角色Action
 * @author Mengfh
 *
 */
@Scope("prototype")
@Controller("roleAction")
@FunctionAnnotationOverride(isAction = true, auth = "角色管理")
public class RoleAction extends AjaxAction<Role> {
	/**日志对象*/
	private final Logger LOG = Logger.getLogger(RoleAction.class);
	
	/**角色实体*/
	private Role entity;
	/**角色实体列表*/
	private List<Role> rows;
	/**角色业务*/
	private IRoleService roleService;
	/**角色id列表拼接字符串*/
	private String authIdStr;

	public Role getEntity() {
		return entity;
	}

	public void setEntity(Role entity) {
		this.entity = entity;
	}
	
	public List<Role> getRows() {
		return rows;
	}

	public void setRows(List<Role> rows) {
		this.rows = rows;
	}

	public String getAuthIdStr() {
		return authIdStr;
	}

	public void setAuthIdStr(String authIdStr) {
		this.authIdStr = authIdStr;
	}

	@Resource(name = "roleService")
	public void setRoleService(IRoleService roleService) {
		this.service = roleService;
		this.roleService = roleService;
	}

	@Override
	protected Role dytEntity() {
		if(this.entity == null) {
			this.entity = new Role();
		}
		return getEntity();
	}

	@Override
	protected void dyEntity(Role t) {
		setEntity(t);
	}
	
	@Override
	public String showList() {
		if(this.entity == null) {
			this.entity = new Role();
		}
		//获取全部权限
		this.entity.setDelFlag(null);
		return super.showList();
	}

	@Override
	public String showListWithoutPager() {
		if(this.entity == null) {
			this.entity = new Role();
		}
		//获取没被禁用的权限
		this.entity.setDelFlag(SysStatic.NORMALDELFLAG);
		return super.showListWithoutPager();
	}

	@Override
	public String showInfo() {
		try {
			if(this.id != null) {
				//根据角色id获取角色的权限列表
				List<String> authIdList = this.roleService.getAuthIdListByRoleId(this.id);
				//设置角色的权限id拼接字符串
				this.authIdStr = StringUtils.join(authIdList, ",");
			}
		} catch (BizException e) {
			LOG.error(e.getMessage());
		}
		return super.showInfo();
	}

	@Override
	public String saveInfo() {
		//将权限id拼接字符串转换为id列表
		if(StringUtils.isNotBlank(this.authIdStr)) {
			String[] authIdArr = this.authIdStr.split(",");
			List<String> authIdList = new ArrayList<String>();
			for (String authId : authIdArr) {
				authIdList.add(authId);
			}
			this.entity.setAuthIdList(authIdList); //设置权限id列表到角色对象中
		}
		return super.saveInfo();
	}
}
